import blue
import trinity
import spaceObject
import turret
import nodemanager
import timecurves
import base
import util
import uthread
import random
import log
import sys
pi = 3.141592653589793
from string import split

class DummyTurret():


class DummyTurretPair():

    def Initialize(self, graphicID):
        self.turrets = [DummyTurret(), DummyTurret()]



    def Release(self):
        return 



    def SetTarget(self, shipID, targetID):
        return 



    def SetAmmoColor(self, ammoTypeID):
        return 



    def StartShooting(self, ammoGFXid = None):
        return 



    def Rest(self):
        return 



    def ActivateFluff(self, fluffname, active):
        return 



    def StopShooting(self):
        return 



entityExplosionsS = ['res:/Emitter/tracerexplosion/NPCDeathS1.blue',
 'res:/Emitter/tracerexplosion/NPCDeathS3.blue',
 'res:/Emitter/tracerexplosion/NPCDeathS4.blue']
entityExplosionsM = ['res:/Emitter/tracerexplosion/NPCDeathM1.blue',
 'res:/Emitter/tracerexplosion/NPCDeathM3.blue',
 'res:/Emitter/tracerexplosion/NPCDeathM4.blue']
entityExplosionsL = ['res:/Emitter/tracerexplosion/NPCDeathL1.blue',
 'res:/Emitter/tracerexplosion/NPCDeathL3.blue',
 'res:/Emitter/tracerexplosion/NPCDeathL4.blue']

class SentryGun(spaceObject.SpaceObject):
    __guid__ = 'spaceObject.SentryGun'

    def __init__(self):
        spaceObject.SpaceObject.__init__(self)
        self.targets = []
        self.modules = {}
        self.fitted = False



    def LoadModel(self, fileName = None, useInstance = False):
        slimItem = sm.StartService('michelle').GetBallpark().GetInvItem(self.id)
        filename = cfg.invtypes.Get(slimItem.typeID).GraphicFile()
        filename_and_turret_type = split(filename, ' ')
        originalFileName = filename_and_turret_type[0]
        trinityFileName = self.GetTrinityVersionFilename(originalFileName)
        try:
            spaceObject.SpaceObject.LoadModel(self, trinityFileName, useInstance)
        except:
            spaceObject.SpaceObject.LoadModel(self, originalFileName, useInstance)
            sys.exc_clear()



    def Assemble(self):
        timecurves.ScaleTime(self.model, (0.9 + (random.random() * 0.2)))
        self.SetStaticRotation()
        slimItem = sm.StartService('michelle').GetBallpark().GetInvItem(self.id)
        self.typeID = slimItem.typeID
        godmaStateManager = sm.StartService('godma').GetStateManager()
        godmaType = godmaStateManager.GetType(slimItem.typeID)
        self.gfxTurretID = godmaType.gfxTurretID
        if settings.user.ui.Get('turretsEnabled', 1):
            self.FitHardpoints()



    def FitHardpoints(self):
        if self.fitted:
            return 
        if (self.model is None):
            self.LogWarn('FitHardpoints - No model')
            return 
        self.fitted = True
        self.modules = {}
        slotcounter = 0
        if turret.TurretSet.Winter2010TurretsEnabled_ToBeRemoved():
            turretSet = turret.TurretSet()
            turretSet.Initialize(util.GraphicFile(self.gfxTurretID), 1)
            self.model.turretSets.append(turretSet.GetTurretSet())
            self.modules[self.id] = turretSet
            self.model.RebuildTurretPositions()
        elif (self.model.__bluetype__ == 'trinity.EveShip2'):
            self.FitHardpointsScene2()
        elif (self.model.__bluetype__ == 'eve.EveShip'):
            self.FitHardpointsDx9()
        else:
            self.FitHardpointsDx8()



    def LookAtMe(self):
        if not self.model:
            return 
        if not self.fitted:
            self.FitHardpoints()



    def FitHardpointsDx8(self):
        self.turrets = nodemanager.FindNodes(self.model, 'locator_turret', 'trinity.TriSplTransform')
        self.turrets.sort(lambda a, b: cmp(a.name, b.name))
        if len(self.turrets):
            turretPair = turret.TurretPair()
            turretPair.Initialize(self.gfxTurretID)
            turretPair.owner = self
            turretPair.turrets[0].owner = self
            turretPair.turrets[1].owner = self
            hardpoint1 = self.turrets[0]
            hardpoint2 = self.turrets[1]
            hardpoint1.object = turretPair.turrets[0].triTurret
            hardpoint2.object = turretPair.turrets[1].triTurret
            turretPair.turrets[0].owner = hardpoint1
            turretPair.turrets[1].owner = hardpoint2
            for each in turretPair.turrets:
                each.guntype = 'e'

        else:
            turretPair = DummyTurretPair()
            turretPair.Initialize(None)
        self.modules[self.id] = turretPair



    def FitHardpointsScene2(self):
        turretPair = turret.Turret_sc2()
        eveTurretPair = turretPair.Initialize(util.GraphicFile(self.gfxTurretID), 'locator_turret_1a', 'locator_turret_1b')
        self.model.turrets.append(eveTurretPair)
        self.modules[self.id] = turretPair
        self.model.RebuildCachedLocatorIndices()



    def FitHardpointsDx9(self):
        turretPair = turret.NewTurret()
        eveTurretPair = turretPair.Initialize(util.GraphicFile(self.gfxTurretID), 'locator_turret_1a', 'locator_turret_1b')
        self.model.turrets.append(eveTurretPair)
        self.modules[self.id] = turretPair
        self.model.RebuildCachedLocatorIndices()



    def Release(self):
        if self.released:
            return 
        for t in getattr(self, 'turrets', []):
            t.object = None

        for turretPair in self.modules.itervalues():
            turretPair.owner = None
            turretPair.Release()
            for turret in getattr(turretPair, 'turrets', []):
                turret.owner = None


        spaceObject.SpaceObject.Release(self)



    def Explode(self):
        if not settings.user.ui.Get('explosionEffectsEnabled', 1):
            return self.exploded
        else:
            if (self.radius < 100.0):
                explosionURL = entityExplosionsS[(self.typeID % 3)]
            elif (self.radius < 400.0):
                explosionURL = entityExplosionsM[(self.typeID % 3)]
            elif (self.radius <= 900.0):
                explosionURL = entityExplosionsL[(self.typeID % 3)]
            if (self.radius <= 900.0):
                return spaceObject.SpaceObject.Explode(self, explosionURL)
            if self.exploded:
                return False
            self.exploded = True
            exlosionBasePath = 'res:/Emitter/tracerexplosion/'
            if (self.radius > 3000.0):
                extraPath = 'StructureDeathRadius1500.blue'
            elif (self.radius > 1500.0):
                extraPath = 'StructureDeathRadius1000.blue'
            else:
                extraPath = 'StructureDeathRadius500.blue'
            explosionURL = (exlosionBasePath + extraPath)
            gfx = trinity.Load(explosionURL.replace('.blue', '.red'))
            if (gfx is None):
                return False
            explodingObjectDisplay = [ x for x in gfx.curveSets if (x.name == 'ExplodingObjectDisplay') ]
            if (gfx.__bluetype__ != 'trinity.EveRootTransform'):
                root = trinity.EveRootTransform()
                root.children.append(gfx)
                root.name = explosionURL
                gfx = root
            self.model.translationCurve = self
            self.model.rotationCurve = None
            gfx.translationCurve = self
            self.explosionModel = gfx
            scene2 = sm.StartService('sceneManager').GetRegisteredScene2('default')
            scene2.objects.append(gfx)
            if len(explodingObjectDisplay):
                explodingObjectDisplay = explodingObjectDisplay[0]
                explodingObjectDisplay.bindings[0].destinationObject = self.model
                self.explosionDisplayBinding = explodingObjectDisplay.bindings[0]
            return True



exports = {'spaceObject.SentryGun': SentryGun}

